﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Threading;
using System.ServiceModel;
using Microsoft.Practices.ObjectBuilder2;

namespace WDA.Core.DynamicReconfiguration
{
	internal class InterHostInterface : IInterHostInterface, IBuilderAware
	{
		private IEnumerable<IInterHostInterface> _remoteHosts;
		private IEnumerable<string> _remoteHostManagementUris;

		[Microsoft.Practices.Unity.Dependency(WDAContainerNames.PersistentInternalContainerName)]
		public IUnityContainer PersistentContainer { get; set; }

		[Microsoft.Practices.Unity.Dependency(WDAContainerNames.InternalContainerName)]
		public IUnityContainer Container { get; set; }

		public InterHostInterface(IEnumerable<string> remoteHostManagementUris)
		{
			_remoteHostManagementUris = remoteHostManagementUris;			
		}

		public void ForceRemoteReconfiguration(long newVersion)
		{
			foreach (IInterHostInterface remoteHost in _remoteHosts)
			{
				try
				{
					remoteHost.InitReconfiguration(newVersion);
				}
				catch (Exception ex)
				{
				}
			}
		}

		#region IInterHostInterface Members
		public void InitReconfiguration(long newVersion)
		{
			RuntimeVersion v = PersistentContainer.Resolve<RuntimeVersion>();
			if (newVersion > v.VersionNumber)
			{
				ReconfigurationProxy manager = PersistentContainer.Resolve<ReconfigurationProxy>();
				manager.EnqueueReconfigurationTask();
			}
		}
		#endregion

		#region IBuilderAware Members
		public void OnBuiltUp(object buildKey)
		{
			IBindingFactory bindingFactory = Container.Resolve<IBindingFactory>();
			_remoteHosts = _remoteHostManagementUris.Select<string, IInterHostInterface>(
				uri => new ChannelFactory<IInterHostInterface>(bindingFactory.CreateBinding(), new EndpointAddress(uri)).CreateChannel());
			_remoteHostManagementUris = null;
		}

		public void OnTearingDown()
		{
		}
		#endregion
	}
}
